package com.huiminpay.merchant.service.impl;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.QiniuUtils;
import com.huiminpay.merchant.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${oss.qiniu.url}")
    private String qiniu_url;
    @Value("${oss.qiniu.accessKey}")
    private String accessKey;
    @Value("${oss.qiniu.secretKey}")
    private String secretKey;
    @Value("${oss.qiniu.bucket}")
    private String bucket;

    /**
     * 文件上传
     * @param multipartFile
     * @return
     * @throws BusinessException
     */
    @Override
    public String upload(MultipartFile multipartFile) throws BusinessException {
        if (multipartFile == null) {
            throw new BusinessException(CommonErrorCode.E_110006);
        }
        byte[] bytes = new byte[0];
        try {
            bytes = multipartFile.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IO流异常");
        }
        String s = UUID.randomUUID().toString();
        //原文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") - 1);
        //新生成文件名称
        String fileName = s + suffix;
        //上传文件
        try {
            QiniuUtils.upload2Qiniu(accessKey, secretKey, bucket, bytes, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100106);
        }
        return qiniu_url + fileName;
    }
}
